package com.xingshentech.ugv.operate.module.login;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xingshentech.ugv.operate.R;
import com.xingshentech.ugv.operate.base.BaseActivity;
import com.xingshentech.ugv.operate.base.UserUtil;
import com.xingshentech.ugv.operate.module.app.log.XsLog;
import com.xingshentech.ugv.operate.module.bean.UserPwdBean;
import com.xingshentech.ugv.operate.module.bean2.AppMenu;
import com.xingshentech.ugv.operate.module.bean2.UserBean;
import com.xingshentech.ugv.operate.module.constant.AppPermission;
import com.xingshentech.ugv.operate.module.constant.Constants;
import com.xingshentech.ugv.operate.module.httpdata.BaseObserverCenter;
import com.xingshentech.ugv.operate.module.httpdata.HttpUtils;
import com.xingshentech.ugv.operate.module.httpdata.JsonResponseFunc;
import com.xingshentech.ugv.operate.module.httpdata.MockApi;
import com.xingshentech.ugv.operate.module.httpdata.RetrofitUtil;
import com.xingshentech.ugv.operate.module.utils.SharedPreferencesUtils;
import com.xingshentech.ugv.operate.module.utils.Utils;
import com.xingshentech.ugv.operate.sdk.UserPwdAdapter;
import com.xingshentech.utils.SecurityUtil;
import com.xstech.library.rxjavahttp.ApiAddress;
import com.xstech.library.rxjavahttp.HeaderInterceptor;
import com.xstech.library.utils.LogUtils;
import com.xstech.library.utils.StringUtils;

//import com.tencent.android.tpush.XGIOperateCallback;
//import com.tencent.android.tpush.XGPushConfig;
//import com.tencent.android.tpush.XGPushManager;

import org.feezu.liuli.timeselector.utils.TextUtil;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_userName)
    EditText et_userName;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.iv_eye)
    ImageView iv_eye;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.tv_ip_config)
    TextView tv_ip_config;
    @BindView(R.id.radio_group)
    RadioGroup radio_group;
    @BindView(R.id.rb_wifi)
    RadioButton rb_wifi;
    @BindView(R.id.layout_login)
    RelativeLayout layout_login;
    @BindView(R.id.layout_ip)
    RelativeLayout layout_ip;
    @BindView(R.id.et_ip)
    EditText et_ip;
    @BindView(R.id.et_port)
    EditText et_port;
    @BindView(R.id.rg_prod_dev)
    RadioGroup rg_prod_dev;
    @BindView(R.id.rb_prod)
    RadioButton rb_prod;
    @BindView(R.id.rb_dev)
    RadioButton rb_dev;
    @BindView(R.id.rb_hw)
    RadioButton rb_hw;
    @BindView(R.id.cb_remember_password)
    CheckBox cb_remember_password;
    @BindView(R.id.cb_ssl_connect)
    CheckBox cb_ssl_connect;
    @BindView(R.id.cb_private_policy)
    CheckBox cb_private_policy;


    @BindView(R.id.tv_private_policy)
    TextView tv_private_policy;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.tv_login, R.id.iv_eye, R.id.tv_ip_config, R.id.tv_cancel, R.id.tv_save, R.id.iv_down})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                // 处理登录按钮点击事件
                if (Constants.noNeedLogo) {
                    setDev_Prod(true);
//                    Intent intent = new Intent(mInstance, MainActivity.class);
//                    Constants.is4gconnect = false;
//                    Constants.OperateVehicleStatus = true;
//                    Constants.WifiConnectPermission = true;
//                    Constants.isWifiSSLConnect = false;
//                    UserUtil.setUserBean(null);
//                    startActivity(intent);
//                    finish();
                    return;
                }
                if (rb_wifi.isChecked()) {
//                    直连登录
                    setDev_Prod(true);
                    netLogin();

                } else {
//                    4G登录
                    setDev_Prod(false);
                    netLogin();
                }
                break;
            case R.id.iv_eye:
                // 处理眼睛图标点击事件
                break;
            case R.id.tv_ip_config:
                showLoginOrSetting(true);
                break;
            case R.id.tv_cancel:
                showLoginOrSetting(false);
                break;
            case R.id.tv_save:
                // 处理保存点击事件
                String value_ip = et_ip.getText().toString().trim();
                String value_port = et_port.getText().toString().trim();
                if (Utils.isIP(value_ip)) {
                    UserUtil.setDomin(value_ip);
                    UserUtil.setDominPort(Integer.parseInt(value_port));
                    showLoginOrSetting(false);
                } else {
                    toast(R.string.is_IP);
                }
                break;
            case R.id.iv_down:
                // 处理向下箭头点击事件

                break;

        }
    }

    UserPwdAdapter mUserPwdAdapter;
    List<UserPwdBean> mUserPwdBeanList;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().getDecorView().setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
        }
        String userName = (String) SharedPreferencesUtils.getParam(Constants.name, "");
        String password = (String) SharedPreferencesUtils.getParam(Constants.password, "");
        if (!TextUtil.isEmpty(userName)) {
            et_userName.setText(userName);
        }
        if (!TextUtil.isEmpty(password)) {
            et_password.setText(password);
        }

        int b = SharedPreferencesUtils.getDev_Prod();
        if (b == 0) {
            rb_prod.setChecked(true);
        } else if (b == 1) {
            rb_dev.setChecked(true);
        } else if (b == 2) {
            rb_hw.setChecked(true);
        }

        rg_prod_dev.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_prod:
                    SharedPreferencesUtils.setDev_Prod(0);
                    break;
                case R.id.rb_dev:
                    SharedPreferencesUtils.setDev_Prod(1);
                    break;
                case R.id.rb_hw:
                    SharedPreferencesUtils.setDev_Prod(2);
                    break;
            }
        });

        et_ip.setText(UserUtil.getDomin());
        et_port.setText(UserUtil.getDominPort() + "");

        mUserPwdBeanList = new ArrayList<>();
//        mUserPwdAdapter = new UserPwdAdapter(this, mUserPwdBeanList);

//        XGPushManager.registerPush(this, new XGIOperateCallback() {
//            @Override
//            public void onSuccess(Object data, int flag) {
//                //token在设备卸载重装的时候有可能会变
//                Log.d("TPush_token", "注册成功1，设备token为：" + data);
//                XsLog.getInstance().save("TPush_token:" + data);
//            }
//
//            @Override
//            public void onFail(Object data, int errCode, String msg) {
//                Log.d("TPush_token", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
//                XsLog.getInstance().save("TPush_token_fail:" + errCode + ",错误信息：" + msg);
//            }
//        });

        radio_group.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_wifi:
                    cb_ssl_connect.setVisibility(View.VISIBLE);
                    break;
                case R.id.rb_4g:
                    cb_ssl_connect.setVisibility(View.GONE);
                    break;

            }
        });
    }




    private void showLoginOrSetting(boolean b) {
        if (b) {
            layout_ip.setVisibility(View.VISIBLE);
            layout_login.setVisibility(View.GONE);
        } else {
            layout_ip.setVisibility(View.GONE);
            layout_login.setVisibility(View.VISIBLE);
        }

    }

    ProdCustomAddress prodCustomAddress;

    //设置测试环境还是生产环境
    private void setDev_Prod(boolean isWifi) {
        int b = SharedPreferencesUtils.getDev_Prod();
        String http = "https://";
        String ws = "wss://";
        if (b == 0) {
            if (prodCustomAddress != null) {
                http = prodCustomAddress.getHttps_head();
                ws = prodCustomAddress.getWss_head();
                ApiAddress.websocketApi = prodCustomAddress.getCenter_ip();
                ApiAddress.api_map = prodCustomAddress.getHttps_head() + prodCustomAddress.getMap_ip() + prodCustomAddress.getMap_port() + "/";
                ApiAddress.api_push = ApiAddress.api_push_prod;
                ApiAddress.websocket_Port = prodCustomAddress.getCenter_ip() + prodCustomAddress.getCenter_port();
                ApiAddress.carrayWebSocket = ws + prodCustomAddress.getFourG_ip() + prodCustomAddress.getFourG_port() + ApiAddress.carrayWebSocket_prod_suffix;
            } else {
//              app调试过程中切换测试生产环境操作如下
                ApiAddress.websocketApi = ApiAddress.websocketApi_prod;
                ApiAddress.api_map = ApiAddress.api_prod;
                ApiAddress.api_push = ApiAddress.api_push_prod;
                ApiAddress.websocket_Port = ApiAddress.websocketApi + ApiAddress.port;
                ApiAddress.carrayWebSocket = ws + ApiAddress.websocketApi + ApiAddress.carrayWebSocket_prod_suffix;
                ApiAddress.api_ota = ApiAddress.api_ota_prod;
                ApiAddress.api_ota_mqtt = ApiAddress.api_ota_mqtt_prod;
            }
//            可能是切换是否使用 SM4 加密，如果 isSM4 = true，可能会启用 国密 SM4 算法，并重新加载 Bouncy Castle 提供者。
            SecurityUtil.setIsSM4(false);
        } else if (b == 1) {
            ApiAddress.websocketApi = ApiAddress.websocketApi_dev;
            ApiAddress.api_map = ApiAddress.api_dev;
            ApiAddress.api_push = ApiAddress.api_push_dev;
            ApiAddress.websocket_Port = ApiAddress.websocketApi + ApiAddress.port_9443;
            ApiAddress.carrayWebSocket = ws + ApiAddress.websocketApi + ApiAddress.carrayWebSocket_dev_suffix;
            ApiAddress.api_ota = ApiAddress.api_ota_dev;
            ApiAddress.api_ota_mqtt = ApiAddress.api_ota_mqtt_dev;
            SecurityUtil.setIsSM4(false);
        } else if (b == 2) {
            ApiAddress.websocketApi = ApiAddress.websocketApi_hw;
            ApiAddress.api_map = ApiAddress.api_hw;
            ApiAddress.api_push = ApiAddress.api_push_dev;
            ApiAddress.websocket_Port = ApiAddress.websocketApi + ApiAddress.port_9443;
            ApiAddress.carrayWebSocket = ws + ApiAddress.websocketApi + ApiAddress.carrayWebSocket_prod_hw_suffix;
            ApiAddress.api_ota = ApiAddress.api_ota_dx;
            ApiAddress.api_ota_mqtt = ApiAddress.api_ota_mqtt_dx;
            SecurityUtil.setIsSM4(false);
        }
        ApiAddress.api_center = http + ApiAddress.websocket_Port + "/";

    }

    private void netLogin() {
        String name = et_userName.getText().toString().trim();
        String psd = et_password.getText().toString().trim();
        if (StringUtils.isEmpty(name)) {
            toast("请输入用户名");
            return;
        }
        if (StringUtils.isEmpty(psd)) {
            toast("请输入登录密码");
            return;
        }
        if (!cb_private_policy.isChecked()) {
            toast("请先阅读并勾选《隐私政策》");
            return;
        }
        HttpUtils.loginAcIsClose = true;
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("rotePath", ApiAddress.userLogin2);
        jsonObject.addProperty("requestMethod", "POST");
        jsonObject.addProperty("apiVersion", "v1");
        JsonObject requestParam = new JsonObject();
        JsonObject vo = new JsonObject();
        vo.addProperty("username", name);
        vo.addProperty("password", psd);
        vo.addProperty("userType", "0");
        vo.addProperty("code", "");
        requestParam.add("vo", vo);
        jsonObject.add("requestParam", requestParam);
//        发送登录请求并处理服务器返回的数据，然后在 主线程更新 UI
//        RetrofitUtil.getInstance().initRetrofit().login(jsonObject)
////                RetrofitUtil.getInstance() → 获取 RetrofitUtil 的单例实例。
////initRetrofit() → 初始化 Retrofit，创建 API 接口对象。
////login(jsonObject) → 调用 login 方法，向服务器发送 jsonObject 作为登录请求参数（一般是用户名、密码）。
//                .subscribeOn(Schedulers.io())
////                指定网络请求的线程，使用 Schedulers.io() 代表 IO 线程（专门用于网络请求、文件读写等操作）。
////这样 login(jsonObject) 不会阻塞主线程。
//                .observeOn(AndroidSchedulers.mainThread())
////                指定数据返回后在哪个线程处理。
////这里使用 AndroidSchedulers.mainThread()，表示 切换到主线程，因为只有主线程才能更新 UI。
//                .map(new JsonResponseFunc<>())
////                对服务器返回的数据进行转换，这里可能是把 JSON 转换成 Java 对象（如 UserBean）
////JsonResponseFunc<> 是一个自定义的 Function，用于解析服务器返回的数据
//                .subscribe(new BaseObserverCenter<UserBean>(this, getString(R.string.Loading)) {
//                    //                    订阅数据流，真正执行网络请求。
////BaseObserverCenter<UserBean> 继承 Observer 或 DisposableObserver，用来接收返回的数据。
//                    @Override
//                    public void onNext(UserBean userBean) {
////                        可以在 onNext 方法里更新 UI
//                        getOperateAppMenu(userBean);
//                    }
//                });

        MockApi mockApi = new MockApi(this);
        UserBean userBean = mockApi.getMockUser(); // 模拟 UserBean
        getOperateAppMenu(userBean);
    }

//    private void getOperateAppMenu(UserBean userBean) {
//        Constants.mAppMenu.clear();
//        HeaderInterceptor.X_Token = userBean.getAccessToken();
//        JsonObject jsonObject = new JsonObject();
//        jsonObject.addProperty("rotePath", ApiAddress.userMenu);
//        jsonObject.addProperty("requestMethod", "GET");
//        jsonObject.addProperty("apiVersion", "v1");
//        JsonObject requestParam = new JsonObject();
//        jsonObject.add("requestParam", requestParam);
//        RetrofitUtil.getInstance().initRetrofit().getAppMenu(jsonObject)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new JsonResponseFunc<>())
//                .subscribe(new BaseObserverCenter<List<AppMenu>>(this, "正在加载资源") {
//                    @Override
//                    public void onNext(List<AppMenu> appMenu) {
//    LogUtils.bean("getOperateAppMenu", appMenu);
////                        refreshMenu(appMenu, userBean);
//
//                    }
//                });
//    }
private void getOperateAppMenu(UserBean userBean) {
    // 使用 MockApi 获取本地数据
    MockApi mockApi = new MockApi(this);
    List<AppMenu> appMenu = mockApi.getMockAppMenu(); // 模拟 AppMenu

    if (userBean != null) {
        Constants.mAppMenu.clear();
        HeaderInterceptor.X_Token = userBean.getAccessToken();
    }

//    Debug.waitForDebugger(); // 代码会在这里暂停，直到连接上 Debugger
//    Log.d("DEBUG", "Debugger 已连接，继续执行代码...");

    if (appMenu != null) {
        refreshMenu(appMenu, userBean); // 模拟返回数据
    } else {
        Log.e("MockAPI", "appMenu 数据加载失败");
    }
}

    public void refreshMenu(List<AppMenu> appMenu, UserBean userBean) {
        List<AppMenu> menus = new ArrayList<>();
        boolean login4g = false;
        for (AppMenu menu : appMenu) {
            if (menu.getResourceCode().equalsIgnoreCase(AppPermission.operate_app_menu)) {
                String parent = menu.getId();
                for (AppMenu menu1 : appMenu) {
                    if (parent.equalsIgnoreCase(menu1.getParentId())) {
                        if (menu1.getResourceCode().equalsIgnoreCase(AppPermission.Login4g)) {
                            login4g = true;
                        } else if (menu1.getResourceCode().equalsIgnoreCase(AppPermission.OperateVehicleStatus)) {
                            Constants.OperateVehicleStatus = true;
                        } else if (menu1.getResourceCode().equalsIgnoreCase(AppPermission.WifiConnectPermission)) {
                            Constants.WifiConnectPermission = true;
                        } else if (menu1.getResourceCode().equalsIgnoreCase(AppPermission.RemoteControl_4G)) {
                            Constants.RemoteControl_4G = true;
                        } else {
                            menus.add(menu1);
                        }
                    }
                }
                break;
            }
        }
        if (rb_wifi.isChecked()) {
            Constants.mAppMenu.addAll(menus);
            toMainActivity(userBean);
        } else {
            if (login4g) {
                Constants.mAppMenu.addAll(menus);
                toMainActivity(userBean);
            } else {
                toast("您没有4G登录权限");
            }
        }
    }

    private void toMainActivity(UserBean userBean) {
        String username = et_userName.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        SharedPreferencesUtils.setParam(Constants.name, username);
//        设置用户信息
        Constants.mUser = userBean;
        UserUtil.setUserBean(userBean);
        UserUtil.setAccessToken(userBean.getAccessToken());

//        打印日志
        String info = "";
        if (!rb_wifi.isChecked()) {
            Constants.is4gconnect = true;
            info = "" + username + "-4G-" + Utils.getFirstInstallTime();
        } else {
            Constants.is4gconnect = false;
            info = "" + username + "-wifi-" + Utils.getFirstInstallTime();
        }

//        XsLog.getInstance().save(info);

//        try {
//            Thread.sleep(6000); // 休眠 6 秒
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }


//        //绑定账号和token
//        List<XGPushManager.AccountInfo> accountInfoList = new ArrayList<>();
//        accountInfoList.add(new XGPushManager.AccountInfo(XGPushManager.AccountType.CUSTOM.getValue(), userBean.getUserInfo().getId() + ""));
//        XGPushManager.upsertAccounts(LoginActivity.this, accountInfoList, new XGIOperateCallback() {
//            @Override
//            public void onSuccess(Object o, int i) {
//                Log.d("TPush_token_bindUserId", userBean.getUserInfo().getId() + "");
//                XsLog.getInstance().save("TPush_token_bindUserId_success:" + userBean.getUserInfo().getId() + "");
//            }
//
//            @Override
//            public void onFail(Object o, int i, String s) {
//                XsLog.getInstance().save("TPush_token_bindUserId_failt:" + userBean.getUserInfo().getId() + i + "=" + s);
//            }
//        });
//
//        //设置是否允许展示应用内消息窗口
//        XGPushConfig.enableShowInMsg(this, true);
//        //创建这个推送通道的分类 后退推送给android 的时候要填ch_id ch_name
//        XGPushManager.createNotificationChannel(this.getApplicationContext(), "9527", "订阅通知", true, true, true, null);
//
        CarListActivity.firstSelec = true;
        Intent intent = new Intent(LoginActivity.this, CarListActivity.class);
        startActivity(intent);
//
//        if (cb_remember_password.isChecked()) {
//            SharedPreferencesUtils.setParam(Constants.password, password);
//            //暂时先屏蔽掉
////            UserPwdBean userPwdBean = new UserPwdBean(null, username, password);
////            DbController.getInstance(LoginActivity.this).getUserPwdController().insert(userPwdBean);
//        } else {
//            SharedPreferencesUtils.setParam(Constants.password, "");
//        }
//        Constants.isWifiSSLConnect = cb_ssl_connect.isChecked();
//        HttpUtils.loginAcIsClose = false;
        finish();

    }
}